<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Upcasting and Downcasting</title>
  <meta
 content="C++ Tutorial: Upcasting and Downcasting"
 name="description" />
  <meta
 content="C++ Tutorial, Upcasting and Downcasting"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">

<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>
<br />
<br />
<br />
<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial - Upcasting and Downcasting</span></div>
<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>   
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>

   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>
<br />
<br />
<img src="images/upcasting_downcasting/NamHanKang.png" alt="NamHanKang"/>
<br />
<br />
<br />

<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="UpDowncasting">Upcasting and Downcasting</div>

<br />
<br />
<div class="subtitle_2nd" id="Upcasting">Upcasting</div>
<p><strong>Upcasting</strong> is converting a derived-class reference or pointer to a base-class. It is always allowed for <strong>public</strong> inheritance, without an explicit type cast. This is a result of the <strong>is-a</strong> relationship between the base and derived classes.</p>
<p>Note that the most important aspect of inheritance is not that it provides member functions for the new class, however. It's the <strong>relationship</strong> expressed between the new class and the base class. This relationship can be summarized by saying, <strong>"The new class is a type of the existing class."</strong> </p>
<pre>
class Parent {
public:
	void sleep() {}
};

class Child: public Parent {
public:
	void gotoSchool(){}
};

int main( ) 
{ 
	Parent parent;
	Child child;

	// upcast - implicit type cast allowed
	Parent *pParent = &child; 

	// downcast - explicit type case required 
	Child *pChild =  (Child *) &parent;

	pParent -> sleep();
	pChild -> gotoSchool();
		
	return 0; 
}
</pre>
<p>A <strong>Child</strong> object is a <strong>Parent</strong> object in that it inherits all the data members and member functions of a <strong>Parent</strong> object. So, anything that we can do a <strong>Parent</strong> object, we can do to a <strong>Child</strong> object. Therefore, a function designed to handle a <strong>Parent</strong> pointer (reference) can without any problems, perform the same acts on a <strong>Child</strong> object. The same idea applies if we pass a pointer to an object as a function argument. Upcasting is <strong>transitive</strong>: if we derive a <strong>Child</strong> class from <strong>Parent</strong>, then <strong>Parent</strong> pointer (reference) can refer to a <strong>Parent</strong>  or a <strong>Child</strong> object.</p>


<br />
<br />
<div class="subtitle_2nd" id="Downcasting">Downcasting</div>
<p>The opposite process, converting a base-class pointer (reference) to a derived-class pointer (reference) is called <strong>downcasting</strong>. Downcasting is not allowed without an explicit type cast. The reason for this restriction is that the <strong>is-a</strong> relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class. </p>
<p>As in the example, we derived <strong>Child</strong> class from a <strong>Parent</strong> class, adding a member function, <strong>gotoSchool()</strong> for getting the size information. It wouldn't make sense to apply the <strong>gotoSchool()</strong> method to a <strong>Parent</strong> object. However, if implicit downcasting were allowed, we could accidentally assign the address of a <strong>Parent</strong> object to a pointer-to-<strong>Child</strong> </p>
<pre>
Child *pChild =  &parent;	// actually this won't compile
				// error: cannot convert from 'Parent *' to 'Child *'
</pre>
<p>
and use the pointer to invoke the <strong>gotoSchool()</strong> method as in the following line.</p>
<pre>
pChild -> gotoSchool();
</pre>
<p>Because a <strong>Parent</strong> isn't a <strong>Child</strong> (a <strong>Parent</strong> need not have a <strong>gotoSchool()</strong> method), the downcasting in the above line can lead to an <strong>unsafe</strong> operation.</p>
C++ provides a special explicit cast called <strong>dynamic_cast</strong> that performs this conversion. Downcasting is the opposite of the basic object-oriented rule, which states objects of a derived class, can always be assigned to variables of a base class.</p>
<p>One more thing about the upcasting: <br />
Because <strong>implicit upcasting</strong> makes it possible for a base-class pointer (reference) to refer to a base-class object or a derived-class object, there is the need for <strong>dynamic binding</strong>. That's why we have <strong>virtual</strong> member functions.</p>
<ul>
	<li><strong>Pointer (Reference)</strong> type: known at <strong>compile</strong> time.</li> 
	<li><strong>Object</strong> type: not known until <strong>run</strong> time.</li> 
</ul>

<br />
<br />
<div class="subtitle_2nd" id="dynamiccasting">Dynamic Casting</div>
<p>The <strong>dynamic_cast</strong> operator answers the question of whether we can <strong>safely</strong> assign the address of an object to a pointer of a particular type.</p>
<p>Here is a similar example to the previous one.</p>
<pre>
#include &lt;string&gt;

class Parent {
public:
	void sleep() {
	}
};

class Child: public Parent {
private:
	std::string classes[10];
public:
	void gotoSchool(){}
};

int main( ) 
{ 
	Parent *pParent = new Parent;
	Parent *pChild = new Child;
		
	Child *p1 = (Child *) pParent;	// #1
	Parent *p2 = (Child *) pChild;	// #2
	return 0; 
}
</pre>
<p>Let look at the lines where we do type cast.</p>
<pre>
Child *p1 = (Child *) pParent;	// #1
Parent *p2 = (Child *) pChild;	// #2
</pre>
<p>Which of the type cast is safe? <br />
The only one guaranteed to be safe is the ones in which the pointer is the same type as the object or else a base type for the object.</p>
<p>Type cast #1 is not safe because it assigns the address of a base-class object (<strong>Parent</strong>) to a derived class (<strong>Child</strong>) pointer. So, the code would expect the base-class object to have derived class properties such as <strong>gotoSchool()</strong> method, and that is false. Also, <strong>Child</strong> object, for example, has a member <strong>classes</strong> that a <strong>Parent</strong> object is lacking.</p>
<p>Type case #2, however, is safe because it assigns the address of a derived-class object to a base-class pointer. In other words, public derivation promises that a <strong>Child</strong> object is also a <strong>Parent</strong> object. </p>
<p>The question of whether a type conversion is safe is more useful than the question of what kind of object is pointed to. The usual reason for wanting to know the type is so that we can know if it's safe to invoke a particular method.</p>
<p>Here is the syntax of <strong>dynamic_cast</strong>.</p>
<pre>
Child *p = <font color="blue">dynamic_cast</font>&lt;Child *&gt;(pParent)
</pre>
<p>This code is asking whether the pointer <strong>pParent</strong> can be type cast safely to the type <strong>Child *</strong>.</p>
<ul>
	<li>It returns the address of the object, if it can. </li>
	<li>It returns <strong>0</strong>, otherwise.</li>
</ul>
<p>How do we use the <strong>dynamic_cast</strong>? </p>
<pre>
void f(<font color="blue">Parent</font>* p) {
 	Child *ptr = <font color="blue">dynamic_cast</font>&lt;Child*&gt;(p);
	 if(ptr) { 
		// we can safely use ptr
	} 
}
</pre> 
<p>In the code, if <strong>(ptr)</strong> is of the type <strong>Child</strong> or else derived directly or indirectly from the type <strong>Child</strong>, the <strong>dynamic_cast</strong> converts the pointer <strong>p</strong> to a pointer of type <strong>Child</strong>. Otherwise, the expression evaluates to <strong>0</strong>, the null pointer.</p>
<p>In other words, we want to check if we can use the passed in pointer <strong>p</strong> before we do some operation on a child class object even though it's a pointer to base class.</p>
<p>"The need for <strong>dynamic_cast</strong> generally arises because we want perform <strong>derived class operation</strong> on a <strong>derived class object</strong>, but we have only a pointer-or reference-to-<strong>base</strong>." -Scott Meyers </p>

<br />
<br />
<img src="images/upcasting_downcasting/NamHanKang2.png" alt="NamHanKang2"/>
<br />
<br />

<div id="rightpanel">
<div align="center">
</div></div>

<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />


<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
